<?php

namespace Common\Model;

use Common\Lib\Upload\ImgManager;
use Think\Model;

class ArticleModel extends Model
{
    protected $_validate = array(
        array('title', 'require', '标题必须填写！', 1),
        array('content', 'require', '内容必须填写！', 1),
        array('category1', 'require', '请正确选择分类！', 1),
        array('category2', 'number', '请正确选择分类！', 2),
    );
    protected $_auto = array(
        array('click', '1'),
        array('audit', '0'),
        array('addtime', 'time', 1, 'function'),
    );

    /**
     * 获取列表
     *
     * @param string $map
     * @param bool   $page
     * @param string $sort
     * @param string $num
     * @param bool   $showuser
     * @return mixed
     */
    public function get_list($map = '', $page = false, $sort = '', $num = '', $showuser = false, $startrow=0)
    {
		//dump($startrow);
        $limit = $num ? $num : 10;
		$maptag['tagid'] = $map['tagid'];
        if ($page) {
            if (empty($maptag['tagid'])) {
                $count = $this->where($map)->count();
            } else {
                $count           = M('ArticleTag')->where($maptag)->count();
            }
            if ($count == 0) {
                return '';
            }
            $Page     = pager($count, $limit);
            $limit    = $Page->firstRow . ',' . $Page->listRows;
            $page_str = $Page->fshow();
        }else{
			 $limit    = $startrow.','.$limit;
		}
        if (!empty($maptag['tagid'])) {
            $tags = D('ArticleTag')->get_tag_tagid($maptag['tagid'], $limit);
            foreach ($tags as $v) {
                $ids[] = $v['aid'];
            }
            unset($map);
            $ids       = is_array($ids) ? implode(",", $ids) : $ids;
            $map['id'] = array('IN', $ids ?: '');
            $result    = $this->where($map)->order('id desc')->select();

        } else {
            $result = $this->where($map)->order($sort)->limit($limit)->select();
        }
		//dump($result);
        foreach ($result as $key => $v) {
            $v['isimg']       = $v['img'];
            $v['img']         = $this->get_article_img($v['img'], $v['id']);
            $v['url']         = $this->view_url($v['id']);
            $v['audit_str']   = $this->get_audit($v['audit']);
            $v['addtime_str'] = daterange($v['addtime']);
            if ($v['category2']) {
                $v['cat'] = D('Category')->find($v['category2']);
            } else {
                $v['cat'] = D('Category')->find($v['category1']);
            }
            $v['content']     = htmlspecialchars_decode($v['content'], ENT_QUOTES);
            $v['content_cut'] = cut_str(strip_tags($v['content']), 110);
            $v['tags']        = D('ArticleTag')->get_tag_qid($v['id']);
            if ($showuser) {
                $v['user'] = D('User')->get_user_one($v['uid'], true, 1);
            }
            $list[] = $v;
        }
        $return['list'] = $list;
        if ($page) {
            $return['count'] = $count;
        } else {
            $return['count'] = count($list);
        }
        $return['page'] = $page_str;
        //print_r($return);
        return $return;
    }

    /**
     * 添加文章
     *
     * @param array $data 文章数据
     * @param int   $uid  发布用户
     */
    public function article_add($data, $uid)
    {
        // 获取文章标签数据
        if (isset($data['tag'])) {
            $tagids = $data['tag'];
            unset($data['tag']);
        }

        $ban = D('UserBan')->chenk_ban($uid);
        if (!empty($ban)) {
            $ret['status']  = false;
            $ret['content'] = "发表失败，您已经被禁言（{$ban['txt']}），禁言结束时间：{$ban['endtime_str']}";
            return $ret;
        }

        $article = new ArticleModel();  // 新建模型实例
        if (!$article->create($data)) {
            $ret['status']  = false;
            $ret['content'] = $article->getError();
            return $ret;
        }
        $article->uid = $uid;
        // 添加文章
        $aid = $article->add();

        $this->on_article_add($aid, $uid);  // 添加文章事件处理

        // 添加文章标签
        if (!empty($tagids) && is_array($tagids)) { // 插入标签
            D('ArticleTag')->batch_add($tagids, $aid, $uid);
        }

        $ret['status']  = true;
        $ret['content'] = '保存成功';
        $ret['aid']     = $aid;

        return $ret;
    }

    /**
     * 添加文章事件行为
     * @param int $aid 文章ID
     * @param int $uid 发布用户ID
     */
    protected function on_article_add($aid, $uid)
    {
        D('User')->update_count($uid, 2);  // 更新文章总数
        D('Task')->exe_add_article($uid);  // 完成发表文章的任务
        D('UserTrack')->add_track($uid, $aid, 3);  // 写入个人动态
    }

    /**
     * 审核文章
     *
     * @param int          $audit
     * @param array|string $ids
     */
    public function article_audit($audit, $ids)
    {
        $map['id'] = array('IN', $ids);

        $list = M('Article')->where($map)->select();
        if ($list) {
            $audit = intval($audit);
            M('Article')->where($map)->save(compact('audit'));
            $this->on_article_audit($list, $audit);
        }
    }

    /**
     * 文章审核事件处理
     *
     * @param array $list  被审核的文章列表
     * @param int   $audit 审核后状态
     */
    protected function on_article_audit($list, $audit)
    {
        $uids = array_column($list, 'uid');

        D('User')->update_count($uids, 2);  // 重新统计用户文章总数
    }

    /**
     * 加精文章
     *
     * @param $excellent
     * @param $ids
     * @return bool|int
     */
    public function article_excellent($excellent, $ids)
    {
        $map['id'] = array('IN', $ids);

        $count = 0;  // 初始化更新数量统计
        $list  = M('Article')->where($map)->select();
        if ($list) {
            $excellent = intval($excellent);
            $count     = M('Article')->where($map)->save(compact('excellent'));
        }

        return $count;
    }

    /**
     * 获取一条文章
     *
     * @param string $id
     * @return mixed
     */
    public function get_one_id($id = '')
    {
        $map['id'] = intval($id);
        $info      = $this->where($map)->find();
        if (!empty($info)) {
            $info['addtime_str'] = daterange($info['addtime']);
            $info['content']     = htmlspecialchars_decode($info['content'], ENT_QUOTES);
            $info['content_cut'] = cut_str(strip_tags($info['content']), 30);
            $info['user']        = D('User')->get_user_one($info['uid'], true, 1);
            $info['tags']        = D('ArticleTag')->get_tag_qid($info['id']);
            if ($info['category2']) {
                $info['cat'] = D('Category')->find($info['category2']);
            } else {
                $info['cat'] = D('Category')->find($info['category1']);
            }
            $info['url'] = RU('article/view', array('id' => $id));
        }
        return $info;
    }

    /**
     * 获取封面
     *
     * @param string $img
     * @param string $id
     * @return string
     */
    public function get_article_img($img = '', $id = '')
    {
        if (empty($img)) {
            $img = __ROOT__ . '/' . C('YTATA_IMG_ARTICLE_DIR') . substr($id, -1) . '.jpg';
        } else {
            $img_info = D('UploadImg')->get_one_id($img);
            if (empty($img_info)) {
                $img = __ROOT__ . '/' . C('YTATA_IMG_ARTICLE_DIR') . substr($id, -1) . '.jpg';
            } else {
                $img_manager = new ImgManager($img_info);
                $img         = $img_manager->url();
            }
        }
        return $img;
    }

    /**
     * 获取问题总数
     *
     * @param int $uid
     * @return int
     */
    public function count_article($uid)
    {
        $map['uid']   = intval($uid);
        $map['audit'] = array('EGT', 0);
        return $this->where($map)->count();
    }

    /**
     * 获取审核状态
     *
     * @param string $audit
     * @return string
     */
    public function get_audit($audit = '0')
    {
        switch ($audit) {
            case '0':
                $audit_str = '<span style="color:#FF0000">未审核</span>';
                break;
            case '1':
                $audit_str = '<span style="color:#009900">已审核</span>';
                break;
            case '-1':
                $audit_str = '<span style="color:#999999">未通过</span>';
                break;
        }
        return $audit_str;
    }

    /**
     * 删除文章
     *
     * @param        $ids
     * @param string $uid
     * @return bool
     */
    public function del_article($ids, $uid = '')
    {
        $wmap['id'] = array('IN', "{$ids}");
        if ($uid <> '') {
            $wmap['uid'] = intval($uid);
        }

        $list = M('Article')->where($wmap)->select();
        if (!empty($list)) {
            $this->where($wmap)->delete();
            $this->on_article_del($list);
        }

        // 删除文章标签
        $map['aid'] = array('IN', $ids);
        $tagids     = M('ArticleTag')->where($map)->getField('id', true);
        if ($tagids) {
            $tagids = implode(',', $tagids);
            D('ArticleTag')->atag_del($tagids);
        }

        return true;
    }

    /**
     * @param array $list
     */
    protected function on_article_del($list)
    {
        $uids = array_column($list, 'uid');

        D('User')->update_count($uids, 2);  // 更新会员文章统计
    }

    /**
     * 更新点赞
     *
     * @param string $id
     * @return bool
     */
    public function inc_praise($id = '')
    {
        $map['id'] = intval($id);
        $this->where($map)->setInc('praise', 1);
        return true;
    }

    /**
     * 获取点赞数量
     *
     * @param string $id
     * @return mixed
     */
    public function get_praise($id = '')
    {
        $map['id'] = intval($id);
        $praise    = $this->field('praise')->where($map)->find();
        return $praise['praise'];
    }

    /**
     * 获取详细页URL
     *
     * @param $id
     * @return string
     */
    public function view_url($id)
    {
        return RU('article/view', array('id' => $id));
    }

    /**
     * 文章点赞
     */
    public function praise($uid, $aid)
    {
        $praise = M('ArticlePraise')->where(compact('uid', 'aid'))->find();
        if ($praise) {
            $res['status'] = 2;
            $res['msg'] = '已点过赞';
            return $res;
        }
        $ret = D('ArticlePraise')->praise_add($uid, $aid);
        // 点赞失败
        if (!$ret['status']) {
            $res['status'] = 0;
            $res['msg'] = $ret['msg'];
            return $res;
        }

        # 点赞成功相关操作
        // 更新主题的点赞数
        $this->where(array('id' => $aid))->setInc('praise');

        $res['status'] = 1;
        $res['msg'] = $ret['msg'];
        $q = $this->field('praise')->find($aid);
        $res['count_praise'] = $q['praise'];
        return $res;
    }
}
?>